#!/bin/sh
# Copyright (C) 2024-2025 KoudaiPC Computer Technologies Co., Ltd.
# script name: huangdi-cleanup-system.sh
# author: david921518@qq.com

. /usr/lib/kpc/posix-arrays.sh

################
# global vars
GLB_WORK_DIR=
GLB_DONE_FILE=
GLB_FIRSTBOOT_ROOT=
GLB_REBOOT_COUNTER=
#GLB_INSTALLED_PKGS=()
declare_i_arr GLB_INSTALLED_PKGS
GLB_NUM_INSTALLED_PKGS=0
GLB_REAL_PATH=
################

whoami=$(which whoami)
if [ x"$whoami" == x ]; then
  user="$USER"
else
  user=$(whoami)
fi

log_kmsg_path="/dev/kmsg"
log_con_path="/dev/tty1"

# 定义日志格式-前缀
log_prefix="[cleanup-system]"
# 定义日志目录和文件名
if [ "$user" == "root" ]; then
  log_file_dir="/var/log/kpc/huangdi"
else
  log_file_dir=~/.local/log/kpc/huangdi
fi
log_file_name="firstboot.log"
log_file_path="$log_file_dir/$log_file_name"

function log_init()
{
  # 文件不存在则创建
  if [ ! -d "$log_file_dir" ]; then
    mkdir -p $log_file_dir
    chmod -R 755 $log_file_dir
  fi
  if [ ! -f "$log_file_path" ]; then
    touch $log_file_path
  fi
}

# 定义日志打印格式
function log()
{
  # 定义日志时间格式
  local curtime=$(date "+%Y-%m-%d %H:%M:%S")
  echo "$curtime $log_prefix $@"
  echo "$curtime $log_prefix $@" >> $log_file_path
  #sleep 1
  if [ "$user" == "root" ]; then
    echo "$log_prefix [kmsg] $@" > $log_kmsg_path
    sleep 1
    #echo "$curtime $log_prefix [con] $@" > $log_con_path
    #sleep 1
  fi
}

function log_from_file()
{
  tmpfile=$@
  if [ ! -f "$tmpfile" ]; then
    log "no file [$tmpfile] to log"
    return 1
  fi

  declare_i_arr lists
  while IFS= read -r line;
  do
    add_i_arr_el lists "$line"
  done <$tmpfile

  # 定义日志时间格式
  local curtime=$(date "+%Y-%m-%d %H:%M:%S")

  #echo "$curtime $log_prefix $@"
  #echo "$curtime $log_prefix $@" >>$log_file_path
  local i=0
  get_i_arr_indices lists indices
  for i in $indices
  do
    echo "$curtime $log_prefix ${line}"
    echo "$curtime $log_prefix ${line}" >>$log_file_path
  done

  if [ "$user" == "root" ]; then
    #echo "$log_prefix [kmsg] $@" >$log_kmsg_path
    get_i_arr_indices lists indices
    for i in $indices
    do
      echo "$curtime $log_prefix ${line}" >$log_kmsg_path
      [ $(( i%10 )) -ne 9 ] || sleep 1
    done

    #sleep 1
  fi
}

# get Work Dir
function get_work_dir()
{
  ################
  # /etc/kpc/firstboot/guest/huangdi-populate-root.sh
  # /etc/kpc/firstboot/guest/huangdi-first-boot.sh
  # /etc/kpc/firstboot/root/etc/rc.local
  # /etc/rc.local
  # /kpcos/distro/huangdi/releases/1.04/targets/x86/64/guest/huangdi-populate-root.sh
  # /kpcos/distro/huangdi/releases/1.04/targets/x86/64/root/etc/rc.local
  ################

  local real_path=$(realpath $0)
  GLB_REAL_PATH="$real_path"
  log "REAL PATH is [$GLB_REAL_PATH]"

  GLB_WORK_DIR=$(dirname "$real_path")
  log "WORK DIR is [$GLB_WORK_DIR]"

  local done_file="${real_path}_done"
  log "done_file=[$done_file]"
  real_done_file=$(realpath "$done_file")
  log "real_done_file=[$real_done_file]"

  GLB_DONE_FILE="$real_done_file"
  log "GLB_DONE_FILE=[$GLB_DONE_FILE]"

  local firstboot_root="$GLB_WORK_DIR/../root"
  log "firstboot_root=[$firstboot_root]"
  real_firstboot_root=$(realpath "$firstboot_root")
  log "real_firstboot_root=[$real_firstboot_root]"

  if [ ! -d $real_firstboot_root ]; then
    log "No firstboot root dir [$real_firstboot_root]."
    exit 1
  fi

  GLB_FIRSTBOOT_ROOT="$real_firstboot_root"
  log "GLB_FIRSTBOOT_ROOT=[$GLB_FIRSTBOOT_ROOT]"

  GLB_REBOOT_COUNTER=$GLB_WORK_DIR/reboot_counter
  log "GLB_REBOOT_COUNTER=$GLB_REBOOT_COUNTER"
  if [ ! -f $GLB_REBOOT_COUNTER ]; then
    echo "0" >$GLB_REBOOT_COUNTER
  fi
}

# loop forever to reboot
function force_reboot()
{
  log "force reboot now!"
  while true; do reboot; sleep 9; done
}

function check_reboot_counter()
{
  local reboot_counter=$(cat $GLB_REBOOT_COUNTER)
  reboot_counter=$((reboot_counter + 1))
  log "reboot counter is [$reboot_counter]"
  if [ $reboot_counter -gt 9 ]; then
    log "reboot too many times, exit now!"
    exit 1
  else
    log "set reboot counter to [$reboot_counter]"
    echo "$reboot_counter" >$GLB_REBOOT_COUNTER
  fi
}

# check WAN interface
function check_wan_iface()
{
  local COUNTER=0
  local dev_array="$(ip route | awk '/default/ {print $5}')"
  local iface_dev=$(echo $dev_array | awk '{print $1}')
  while [ "$iface_dev"x == x ]; do
    sleep 1
    COUNTER=$((COUNTER + 1))
    if [ $COUNTER -gt 29 ]; then
      log "Can't get default route device interface, exit now"
      exit 1
    fi
    dev_array="$(ip route | awk '/default/ {print $5}')"
    iface_dev=$(echo $dev_array | awk '{print $1}')
  done

  COUNTER=0
  local WAN_IP=$(ip addr show $iface_dev | grep "inet" | head -n 1 | awk '/inet/ {print $2}' | cut -d'/' -f1)
  while [ "${WAN_IP}"x == x ]; do
    sleep 1
    COUNTER=$((COUNTER + 1))
    if [ $COUNTER -gt 29 ]; then
      log "Can't get WAN IP address, reboot now"
      force_reboot
    fi
    WAN_IP=$(ip addr show $iface_dev | grep "inet" | head -n 1 | awk '/inet/ {print $2}' | cut -d'/' -f1)
  done
  log "WAN IP=[${WAN_IP}]"
}

# check WAN interface
function ubus_check_wan_iface()
{
  local COUNTER=0
  WAN_IP=$(ubus call network.interface.wan status | grep "address" | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')
  while [ "${WAN_IP}"x == x ]; do
    sleep 1
    COUNTER=$((COUNTER + 1))
    if [ $COUNTER -gt 29 ]; then
      log "Can't get WAN IP address, reboot now"
      force_reboot
    fi
    WAN_IP=$(ubus call network.interface.wan status | grep "address" | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')
  done
  log "WAN IP=[${WAN_IP}]"
}

# save installed packages list
function save_pkg_list()
{
  if [ "$1" == "" ]; then
    log "save_pkg_list() filename is empty, do nothing!"
    return
  fi
  local list_file="$PWD"/$1
  log "save $inst_type packages list to $list_file"
  [ -f $list_file ] || opkg list-installed >$list_file
}

# start kpc-heartbeat
function start_heartbeat()
{
  heartbeat_conf_dir=/etc/kpc
  heartbeat_conf_file=/etc/kpc/heartbeat.conf
  heartbeat_file=/usr/sbin/kpc-heartbeat.sh
  heartbeat_lock=/tmp/kpc-hearbeat.lock
  if [ ! -f $heartbeat_conf_file ]; then
    mkdir -p $heartbeat_conf_dir
    echo 9 >$heartbeat_conf_file
  fi
  if [ -x $heartbeat_file ]; then
    log "start kpc-heartbeat"
    (flock -n $heartbeat_lock -c "($heartbeat_file)")&
  fi
}

# 0. init script
log_init
log "[cleanup-system] START"
get_work_dir
if [ -f $GLB_DONE_FILE ]; then
  log "exist file $GLB_DONE_FILE , exit now"
  exit 1
fi
cd "$GLB_WORK_DIR"
check_reboot_counter
start_heartbeat
#check_wan_iface
ubus_check_wan_iface
save_pkg_list pre_cleanup_system_pkgs.txt

log "PATH=[$PATH]"

# 1. remove dropbear keys
rm -f /etc/dropbear/dropbear_ed25519_host_key
rm -f /etc/dropbear/dropbear_rsa_host_key

# 2. remove nginx _lan key/cert
rm -f /etc/nginx/conf.d/_lan.key
rm -f /etc/nginx/conf.d/_lan.crt

save_pkg_list post_cleanup_system_pkgs.txt
touch $GLB_DONE_FILE
sync
sleep 1

log "[cleanup-system] EXIT"
sleep 1

# restart system
reset_reboot_counter
#poweroff
